<?php

namespace app\admin\controller\admin;
use app\common\controller\Backend;
use app\common\controller\RedisAdmin;
use think\Db;
use think\Loader;

/**
 * 用户管理
 *
 * @icon fa fa-file-text-o
 */
class Distributor extends Backend
{
    /**
     * School模型对象
     */
    protected $searchFields = 'id,nick_name,phone,user_province';
    protected $model = null;
    protected $put_model = null;
    protected $uid = null;
    protected $group_id= 0;
    protected $noNeedRight = ['account_audit','getProvinceCity','getGroupInfo','send_audit_result'];
//    protected $noNeedLogin = ['update_user'];
    protected $isSuperAdmin = false;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\admin\Distributor();
        $this->put_model = new \app\admin\model\admin\PutCard();
        //是否超级管理员
        $this->isSuperAdmin = $this->auth->isSuperAdmin();
        $charge_person = Db::name('ca_auth_group')
            ->field('id group_id,name group_name')
            ->where(['status'=>'normal'])
            ->select();
        $arr = [[
            'group_id'=>0,
            'group_name'=>'全部',
        ]];
        foreach ($charge_person as $ww=>$vv){
            $arr[$ww+1]['group_id'] = $vv['group_id'];
            $arr[$ww+1]['group_name'] = $vv['group_name'];
        }
        $this->assignConfig('charge_person', $arr);
        $this->group_id = $this->auth->getGroupIds()[0];
        $this->uid = getAllChildId($this->group_id);
    }

    /**
      * 渠道管理
     */
    public function index()
    {

        $request = $this->request->request();
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
      //      list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //  list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where = [];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_new =[];
            $year = isset($request['year'])?$request['year']:'';
            $distributor_type = isset($request['distributor_type'])?$request['distributor_type']:'';
            $group_id = isset($request['group_id'])?$request['group_id']:0;
            $admin_id = isset($request['admin_id'])?$request['admin_id']:0;
            $distributor = isset($request['distributor'])?$request['distributor']:'';
            $city = isset($request['city'])?$request['city']:'全部';
            $audit_status = isset($request['audit_status'])?$request['audit_status']:'全部';
            $province = isset($request['province'])?$request['province']:'全国';
            if ($year) $where_new['year'] = $year;
            if ($distributor) $where_new['distributor_name'] = ['like','%'.$distributor.'%'];
            if ($distributor_type) $where_new['distributor_type'] = $distributor_type;
            if ($audit_status != '全部') $where_new['audit_status'] = $audit_status;
            if ($group_id != 0) $where_new['ac.group_id'] = $group_id;
            if ($admin_id != 0) $where_new['creater_id'] = $admin_id;
            if ($province != '全国') $where_new['province'] = $province;
            if ($city != '全部') $where_new['city'] = $city;
//            if($this->auth->id != 1){
//                $where_new['creater_id'] = $this->auth->id;
//            }
//            $new_where = [];
            $where_new['a.province_id'] = ['>',0];
            if($this->auth->id >1){
                $group_info = Db::name('ca_auth_group')->where(['status'=>'normal'])->select();
                $child_group = getAllChild($group_info,$this->group_id);
                array_push($child_group, $this->group_id);
                $uid_arr = Db::name('ca_auth_group_access')
                    ->alias('ac')
                    ->join('ca_admin a','a.id =ac.uid','right')
                    ->where(['group_id'=>['in',$child_group],'status'=>'normal'])
                    ->column('uid');
                //  $user_id_arr = Db::name('ca_admin')->where(['id'=>['in',$uid_arr],'status'=>'normal'])->column('id');
                $where_new['creater_id'] = ['in',$uid_arr];
                // var_dump($where_new['creater_id']);
            }
           // $where_new['type'] = 1;
            $total = $this->model
                ->alias('a')
                ->join('app_ca_auth_group_access ac','ac.uid = a.creater_id','left')
                ->join('app_ca_auth_group g','g.id = ac.group_id','left')
                ->where($where)
                ->where($where_new)
                ->count();
            $list =  $this->model
                ->where($where_new)
                ->where($where)
                ->alias('a')
                ->join('app_ca_auth_group_access ac','ac.uid = a.creater_id','left')
                ->join('app_ca_auth_group g','g.id = ac.group_id','left')
                ->field('a.*,ac.group_id')
              //  ->where($con)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $sql = $this->model->getLastSql();
            foreach ($list as $w=>&$v){
                $v['new_address'] = $v['province'].'-'.$v['city'];
                $v['price'] = $v['price']/100;
               // $num = Db::name('card_log')->where(['card_type'=>0,'distributor_id'=>$v['id']])->count('id');
              //  $v['activate_num'] = Db::name('card_log')->where(['card_type'=>0,'is_activate'=>1,'distributor_id'=>$v['id']])->count('id');
              //  $v['put_amount'] = $v['price']*$num;
                $card_put_info = Db::name('card_put_info')
                    ->where(['audit_status'=>['in',[1,3,4]],'distributor_id'=>$v['id'],'put_type'=>0])
                    ->field('sum(put_price*put_num) as total_price')->find();
                //   var_dump($card_put_info);
                //  $num = Db::name('card_log')->where(['card_type'=>0,'distributor_id'=>$v['id']])->count('id');
                $v['activate_num'] = Db::name('card_log')->where(['is_activate'=>1,'distributor_id'=>$v['id']])->count('id');
                $v['put_amount'] = $card_put_info['total_price']/100;
            }
            $result = array("total" => $total, "rows" => $list,"sql"=>$sql);

            return json($result);
        }
        $this->assign('province', get_pro());
        $this->assign('city', []);
       // $this->assign('dis_num', $dis_num);
        return $this->view->fetch();
    }
    /**
     * 赠送审核列表
     */
    public function send_list()
    {
        $request = $this->request->request();
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            //      list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //  list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where = [];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_new =[];
            $year = isset($request['year'])?$request['year']:'';
            $distributor_type = isset($request['distributor_type'])?$request['distributor_type']:'';
            $group_id = isset($request['group_id'])?$request['group_id']:0;
            $admin_id = isset($request['admin_id'])?$request['admin_id']:0;
            $distributor = isset($request['distributor'])?$request['distributor']:'';
            $city = isset($request['city'])?$request['city']:'全部';
            $audit_status = isset($request['audit_status'])?$request['audit_status']:'全部';
            $begin_time = isset($request['begin_time'])?$request['begin_time']:'';
            $end_time = isset($request['end_time'])?$request['end_time']:'';
            $province = isset($request['province'])?$request['province']:'全国';
            if ($year) $where_new['a.year'] = $year;
            if ($distributor) $where_new['distributor_name'] = ['like','%'.$distributor.'%'];
            if ($distributor_type) $where_new['distributor_type'] = $distributor_type;
            if ($begin_time) $where_new['create_time'] = ['between',[$begin_time,$end_time]];
            if ($audit_status != '全部') $where_new['a.audit_status'] = $audit_status;
            if ($group_id != 0) $where_new['ac.group_id'] = $group_id;
            if ($admin_id != 0) $where_new['creater_id'] = $admin_id;
            if ($province != '全国') $where_new['a.province'] = $province;
            if ($city != '全部') $where_new['a.city'] = $city;
//            if($this->auth->id != 1){
//                $where_new['admin_id'] = $this->auth->id;
//            }
//            if($this->group_id>2){
//                $where_new['creater_id']=['in',$this->uid];
//            }
            if($this->auth->id >1){
                $group_info = Db::name('ca_auth_group')->where(['status'=>'normal'])->select();
                $child_group = getAllChild($group_info,$this->group_id);
                array_push($child_group, $this->group_id);
                $uid_arr = Db::name('ca_auth_group_access')
                    ->alias('ac')
                    ->join('ca_admin a','a.id =ac.uid','right')
                    ->where(['group_id'=>['in',$child_group],'status'=>'normal'])
                    ->column('uid');
                //  $user_id_arr = Db::name('ca_admin')->where(['id'=>['in',$uid_arr],'status'=>'normal'])->column('id');
                $where_new['creater_id'] = ['in',$uid_arr];
                // var_dump($where_new['creater_id']);
            }
            $where_new['put_type'] = 1 ;
            $total = $this->put_model
                ->alias('a')
                ->join('app_ca_auth_group_access ac','ac.uid = a.admin_id','left')
                ->join('app_ca_auth_group g','g.id = ac.group_id','left')
                ->join('app_cd_admin cd','cd.id = a.distributor_id','left')
                ->where($where)
                ->where($where_new)
                ->count();
            $list =  $this->put_model
                ->where($where_new)
                ->where($where)
                ->alias('a')
                ->join('app_ca_auth_group_access ac','ac.uid = a.admin_id','left')
                ->join('app_ca_auth_group g','g.id = ac.group_id','left')
                ->join('app_cd_admin cd','cd.id = a.distributor_id','left')
                ->field('a.*,ac.group_id')
                //  ->where($con)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $sql = $this->model->getLastSql();
            foreach ($list as $w=>&$v){
                $v['new_address'] = $v['province'].'-'.$v['city'];
                $v['put_price'] = $v['put_price']/100;
                $v['put_amount'] = $v['put_price']*$v['put_num'];
                $v['admin_name'] = Db::name('ca_admin')->where(['id'=>$v['admin_id']])->value('nickname');
                $distributor_info = get_distributor_info($v['distributor_id']);
                $v['distributor_name'] = $distributor_info['distributor_name'];
                $v['distributor_type'] = $distributor_info['distributor_type'];
            }
            $result = array("total" => $total, "rows" => $list,"sql"=>$sql);

            return json($result);
        }
        $this->assign('province', get_pro());
        $this->assign('city', []);
        return $this->view->fetch();
    }
    /**
     * 发行审核列表
     */
    public function put_list()
    {
        $request = $this->request->request();
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            //      list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            //  list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where = [];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_new =[];
            $year = isset($request['year'])?$request['year']:'';
            $distributor_type = isset($request['distributor_type'])?$request['distributor_type']:'';
            $group_id = isset($request['group_id'])?$request['group_id']:0;
            $admin_id = isset($request['admin_id'])?$request['admin_id']:0;
            $distributor = isset($request['distributor'])?$request['distributor']:'';
            $city = isset($request['city'])?$request['city']:'全部';
            $audit_status = isset($request['audit_status'])?$request['audit_status']:'全部';
            $begin_time = isset($request['begin_time'])?$request['begin_time']:'';
            $end_time = isset($request['end_time'])?$request['end_time']:'';
            $province = isset($request['province'])?$request['province']:'全国';
            if ($year) $where_new['year'] = $year;
            if ($distributor) $where_new['distributor_name'] = ['like','%'.$distributor.'%'];
            if ($distributor_type) $where_new['distributor_type'] = $distributor_type;
            if ($begin_time) $where_new['create_time'] = ['between',[$begin_time,$end_time]];
            if ($audit_status != '全部') $where_new['a.audit_status'] = $audit_status;
            if ($group_id != 0) $where_new['ac.group_id'] = $group_id;
            if ($admin_id != 0) $where_new['creater_id'] = $admin_id;
            if ($province != '全国') $where_new['a.province'] = $province;
            if ($city != '全部') $where_new['a.city'] = $city;
//            if($this->auth->id != 1){
//                $where_new['admin_id'] = $this->auth->id;
//            }

            if($this->auth->id >1){
                $group_info = Db::name('ca_auth_group')->where(['status'=>'normal'])->select();
                $child_group = getAllChild($group_info,$this->group_id);
                array_push($child_group, $this->group_id);
                $uid_arr = Db::name('ca_auth_group_access')
                    ->alias('ac')
                    ->join('ca_admin a','a.id =ac.uid','right')
                    ->where(['group_id'=>['in',$child_group],'status'=>'normal'])
                    ->column('uid');
                //  $user_id_arr = Db::name('ca_admin')->where(['id'=>['in',$uid_arr],'status'=>'normal'])->column('id');
                $where_new['creater_id'] = ['in',$uid_arr];
                // var_dump($where_new['creater_id']);
            }
            $where_new['put_type'] = 0 ;
            $total = $this->put_model
                ->alias('a')
                ->join('app_ca_auth_group_access ac','ac.uid = a.admin_id','left')
                ->join('app_ca_auth_group g','g.id = ac.group_id','left')
                ->join('app_cd_admin cd','cd.id = a.distributor_id','left')
                ->where($where)
                ->where($where_new)
                ->count();
            $list =  $this->put_model
                ->where($where_new)
                ->where($where)
                ->alias('a')
                ->join('app_ca_auth_group_access ac','ac.uid = a.admin_id','left')
                ->join('app_ca_auth_group g','g.id = ac.group_id','left')
                ->join('app_cd_admin cd','cd.id = a.distributor_id','left')
                ->field('a.*,ac.group_id')
                //  ->where($con)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $sql = $this->model->getLastSql();
            foreach ($list as $w=>&$v){
                $v['new_address'] = $v['province'].'-'.$v['city'];
                $v['put_price'] = $v['put_price']/100;
                $v['put_amount'] = $v['put_price']*$v['put_num'];
                $v['admin_name'] = Db::name('ca_admin')->where(['id'=>$v['admin_id']])->value('nickname');
                $distributor_info = get_distributor_info($v['distributor_id']);
                $v['distributor_name'] = $distributor_info['distributor_name'];
                $v['distributor_type'] = $distributor_info['distributor_type'];
            }
            $result = array("total" => $total, "rows" => $list,"sql"=>$sql);

            return json($result);
        }
        $this->assign('province', get_pro());
        $this->assign('city', []);
        return $this->view->fetch();
    }

    /**
 * 审核
 * @return string|\think\response\Json
 */
    public function audit($ids=null){  //审核
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row);
        $this->view->assign("sh_id", $ids);
        return $this->view->fetch();
    }
    /**
 * 审核
 * @return string|\think\response\Json
 */
    public function account_audit(){  //审核
        $sh_id = $this->request->request("sh_id");
        $row = $this->model->get($sh_id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $sh_id = $this->request->request("sh_id");
            $status = $this->request->request("status");
            if ($sh_id) {
                try {
                    $update['audit_status'] = $status;
                    $update['updatetime'] = time();
                    // $where['id'] = $sh_id;
//                    $params['update_time'] = time();
//                    $params['admin_id'] = $this->auth->id;
//                    Db::name('province_city_region')->where(['city_id'=>$ids])->update(['city'=>$params['city'],'update_time'=>time()]);
                    $result = $this->model->where(['id'=>$sh_id])->update($update);
                    if ($result !== false) {
                        if($status == 1){
                            $id = DB::name('cd_auth_group_access')->where(['uid' => $sh_id])->field('uid')->find();
                            if(!$id){
                                DB::name('cd_auth_group_access')->insert(['uid' => $sh_id, 'group_id' =>70]);
                            }else{
                                DB::name('cd_auth_group_access')->where(['uid' => $sh_id])->update(['group_id' => 70]);
                            }
                        }
                        //  DB::name('auth_group_access')->insert(['uid' => $result, 'group_id' => $post['access_group']]);

                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();

    }

    /**
     * 关闭
     * @return string|\think\response\Json
     */
    public function close($ids=null){  //审核
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $update['status'] = 'hidden';
        $update['updatetime'] = time();
        $result = $this->model->where(['id'=>$ids])->update($update);
        if($result){
            $this->success();
        }
        $this->error();
    }
    /**
     * open
     * @return string|\think\response\Json
     */
    public function open($ids=null){  //审核
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $update['status'] = 'normal';
        $update['updatetime'] = time();
        $result = $this->model->where(['id'=>$ids])->update($update);
        if($result){
            $this->success();
        }
        $this->error();
    }

    public function  getProvinceCity(){
        // echo phpinfo();
       // $getProvinceInfo = RedisAdmin::getInstance(1)->get('getProvinceCity');
        $getProvinceInfo = null;
        if(!$getProvinceInfo){
            $province_info = Db::name('province')->where(['is_del'=>0,'id'=>['>',1]])->select();
            $arr = [[
                'label'=>'全国',
                'children'=>[['label'=>'全部']],
            ]];
            foreach ($province_info as $w=>&$v){
                // $arr[$w]['value'] = $v['id'];
                $arr[$w+1]['label'] = $v['name'];
                $arr[$w+1]['children'] =$this->getW($v['id']);
            }

          //  $set = RedisAdmin::getInstance(1)->set('getProvinceCity',json_encode($arr),24*60*60);
        }else{
            //  var_dump($getProvinceInfo);
            //   var_dump(json_decode($getProvinceInfo,true));
            $arr = json_decode($getProvinceInfo,true);
        }
        $data = [
            'info'=>json_encode($arr,JSON_UNESCAPED_UNICODE )
        ];
        $this->success('请求成功','',$data);
    }

    public function getW($province_id,$type=1){
        if($type==1){
            $province_info = Db::name('province_city')->where(['province_id'=>$province_id,'is_del'=>0])->select();
            $arr_p = [];
            $arr_p = [['label'=>'全部']];
            foreach ($province_info as $ww=>&$vv){
                // $arr_p[$ww]['value'] = $vv['id'];
                $arr_p[$ww+1]['label'] = $vv['city'];
//                $child = $this->getW($vv['id'],2);
//                if(!empty($child)){
//                    $arr_p[$ww+1]['children'] = $child;
//                }

            }
            $arrr= $arr_p;
        }else{
            $province_info = Db::name('province_city_region')->where(['city_id'=>$province_id,'is_del'=>0])->select();
            $arr_c = [['label'=>'全部']];
            foreach ($province_info as $www=>&$vvv){
                // $arr_c[$www]['value'] = $vvv['id'];
                $arr_c[$www+1]['label'] = $vvv['region'];
            }
            return $arr_c;
            //$arrr= $arr_c;
        }

        return $arr_p;

    }


    public function  getGroupInfo(){
        $group_info = Db::name('ca_auth_group')->where(['status'=>'normal'])->select();
        $arr = [
          ['label'=>'全部','id'=>0,'children'=>[['label'=>'全部','id'=>0]]]
        ];
        foreach ($group_info as $w=>&$v){
            // $arr[$w]['value'] = $v['id'];
            $arr[$w+1]['label'] = $v['name'];
            $arr[$w+1]['id'] = $v['id'];
            $access_info = Db::name('ca_auth_group_access')->where(['group_id'=>$v['id']])->column('uid');
            $user_info = Db::name('ca_admin')->where(['id'=>['in',$access_info],'status'=>'normal'])->field('id,nickname')->select();
            $arr_p = [];
            $arr_p = [['label'=>'全部','id'=>0]];
            foreach ($user_info as $ww=>&$vv){
                // $arr_p[$ww]['value'] = $vv['id'];
                $arr_p[$ww+1]['label'] = $vv['nickname'];
                $arr_p[$ww+1]['id'] = $vv['id'];

            }
            $arr[$w+1]['children'] =$arr_p;
        }
        $data = [
            'info'=>json_encode($arr,JSON_UNESCAPED_UNICODE )
        ];
        $this->success('请求成功','',$data);
    }

    /**
     * 审核
     * @return string|\think\response\Json
     */
    public function put_audit($ids=null){  //审核
        $type = input('type');
       // var_dump($type);
        $row = $this->put_model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
       // var_dump($row);
        $arr_img = explode(',',$row['put_image']);
        foreach ($arr_img as $w=>&$v){
            $v = 'https://fjgk-file.oss-cn-hangzhou.aliyuncs.com/'.$v;
        }

        $this->view->assign("type", $type);
        $this->view->assign("row", $row);
        $this->view->assign("arr_img", $arr_img);
        $this->view->assign("sh_id", $ids);
        return $this->view->fetch();
    }

    /**
     * 审核
     * @return string|\think\response\Json
     */
    public function send_audit_result(){  //审核
        $sh_id = $this->request->request("sh_id");
        $row = $this->put_model->get($sh_id);
       // echo $this->put_model->getLastSql();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $sh_id = $this->request->request("sh_id");
            $status = $this->request->request("status");
            if ($sh_id) {
                try {
                    $update['audit_status'] = $status;
                    $update['update_time'] = time();
                    $update['put_time'] = time();
                    // $where['id'] = $sh_id;
//                    $params['update_time'] = time();
//                    $params['admin_id'] = $this->auth->id;
//                    Db::name('province_city_region')->where(['city_id'=>$ids])->update(['city'=>$params['city'],'update_time'=>time()]);
                    $result = $this->put_model->where(['id'=>$sh_id])->update($update);
                    if ($result !== false) {
                        if($status==1){
                            Db::startTrans();
                            $create_result = $this->put_model->createCard($row);  //制卡
                            if($create_result['code'] == 500){
                                Db::rollback();
                                $this->error($create_result['msg']);
                            }
//                            $are_result = $this->put_model->addAreaPerformance($row); //区域业绩统计
//                            if($are_result['code'] == 500){
//                                Db::rollback();
//                                $this->error($are_result['msg']);
//                            }
//                            $staff_result = $this->put_model->addStaffPerformance($row); //员工业绩统计
//                            if($staff_result['code'] == 500){
//                                Db::rollback();
//                                $this->error($staff_result['msg']);
//                            }
                            Db::commit();
                        }
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();

    }
}
